<template>
  <div class="mail_sign_do_box">
    <div class="mailSignAddOrEdit" v-show="showFlag === 'update'">
      <el-form :model="mailSignatureClone" ref="mailSignatureClone" >
        <div>{{$t('configLazyLoad.channel.mailTip26')}}</div>
        <el-form-item prop="name" class="mail_signature_title">
          <el-input v-model.trim="mailSignatureClone.name"></el-input>
        </el-form-item>
        <el-form-item prop="content">
          <div>{{$t('configLazyLoad.channel.mailTip31')}}</div>
          <div id="signatureInfo" class="unknown-question padding-top"></div>
          <el-input size="small" v-model.trim="mailSignatureClone.content" style="display:none;"></el-input>
        </el-form-item>
        <div class="btn_box">
          <el-button type="primary" class="submit primary_btn" @click="submit('mailSignatureClone')">{{$t('public.save')}}</el-button>
        </div>
      </el-form>
    </div>
    <div class="mailSignShow" v-show="showFlag === 'preview'">
      <div class="sign_preview" v-html="mailSignatureClone.content">
      </div>
    </div>
  </div>
</template>
<script>
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  import {uploadTo7moorEmailDomain} from '@/utils/qiniuUtils'
  import { deepClone, filterXSS } from '@/utils/m7Utils'
  export default {
    name: 'MailSignaturnEdit',
    data () {
      return {
        rules: {
          name: [
            {required: true, message: this.$t('configLazyLoad.channel.mailTip32'), trigger: 'blur'}
          ]
        },
        editor: {},
        m7uploaders: [],
        mailSignatureClone: {
          name: '',
          content: ''
        }
      }
    },
    props: {
      mailSignature: {
        type: Object,
        default () {
          return {
            name: '',
            content: ''
          }
        }
      },
      flag: {
        type: String,
        default: ''
      },
      todoFlag: {
        type: String,
        default: 'add'
      },
      updateRandom: {
        type: Number,
        default: 0
      },
      formResetRandom: {
        type: Number,
        default: 0
      }
    },
    watch: {
//      切换左侧修改的时候，右侧的内容应该跟着变换
      updateRandom () {
        if (this.mailSignature) {
          this.mailSignatureClone = deepClone(this.mailSignature)
        } else {
          this.mailSignatureClone = {
            name: '',
            content: ''
          }
        }
        this.editor.txt.html(filterXSS(this.mailSignatureClone.content))
      },
      formResetRandom () {
        this.refresh('mailSignatureClone')
      },
      mailSignature () {
        if (this.mailSignature) {
          this.mailSignatureClone = deepClone(this.mailSignature)
        } else {
          this.mailSignatureClone = {
            name: '',
            content: ''
          }
        }
      }
    },
    computed: {
      showFlag () {
        return this.flag
      },
      todoFlagNew () {
        return this.todoFlag
      },
      sessionUserId () {
        return this.$store.state.session.user._id
      }
    },
    methods: {
      submit (formName) {
        let that = this
        that.$refs[formName].validate((valid) => {
          if (valid) {
            let text = that.editor.txt.html().replace('<p>', '').replace('<br>', '').replace('</p>', '')
            console.log(that.editor.txt.html())
            if (!that.editor.txt.text() && !text) {
              that.$message.error(this.$t('configLazyLoad.channel.mailTip33'))
              return
            }
            that.mailSignatureClone.content = that.editor.txt.html()
            let data = {
              obj: that.mailSignatureClone,
              todo: that.todoFlagNew
            }
            that.$emit('submit', data)
          }
        })
      },
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
          self.mailSignatureClone.content = self.editor.txt.html()
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorEmailDomain(this.sessionUserId, 'w-e-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      refresh (formName) {
        if (this.$refs[formName]) {
          this.$refs[formName].resetFields()
        }
      }
    },
    beforeMount () {
      if (this.mailSignature) {
        this.mailSignatureClone = deepClone(this.mailSignature)
      }
    },
    mounted () {
      this.editor = new Editor('#signatureInfo')
      this.editor.config.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify'  // 对齐方式
      ]
      this.editor.config.pasteTextHandle = filterXSS
      this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
      let that = this
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      this.editor.config.lang = editLang
      this.editor.config.onchange = (html) => {
        // html 即变化之后的内容
        that.mailSignatureClone.content = that.editor.txt.html()
      }
      this.editor.config.zIndex = 100
      this.editor.create()
      this.editor.txt.html(filterXSS(this.mailSignatureClone.content))
      let div = document.createElement('div')
      div.className = 'w-e-menu'
      div.style.cssText = 'z-index:101;'
      let span = document.createElement('i')
      span.className = 'w-e-icon-image'
      span.id = 'w-e-img-icon'
      div.appendChild(span)
      document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
      this.initUploadImageFile()
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  .mail_sign_do_box
    padding 20px
  .mail_signature_title
    margin-bottom 10px
  .submit
    float right
  .sign_preview
    width 100%
    max-height 300px
    padding 20px
    box-sizing border-box
</style>
